package cn.com.cifi.mars.web.action.projectConsole;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

import cn.com.cifi.mars.bean.dto.AllProjectIndexDto;
import cn.com.cifi.mars.bean.dto.ProjectByStagesDto;
import cn.com.cifi.mars.bean.dto.ProjectCountDto;
import cn.com.cifi.mars.bean.dto.ProjectStagesDto;
import cn.com.cifi.mars.bean.dto.ProjectStagesVersionDto;
import cn.com.cifi.mars.bean.dto.ProjectUnderwayDto;
import cn.com.cifi.mars.bean.dto.ProjectValueDto;
import cn.com.cifi.mars.bean.vo.workBench.AllProjectIndexVO;
import cn.com.cifi.mars.bean.vo.workBench.ProjectIndexVO;
import cn.com.cifi.mars.bean.vo.workBench.ProjectOverviewVO;
import cn.com.cifi.mars.bean.vo.workBench.ProjectStageVO;
import cn.com.cifi.mars.bean.vo.workBench.ProjectUnderwayVO;
import cn.com.cifi.mars.bean.vo.workBench.ProjectVersionVO;
import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.HrOrgTypeEunm;
import cn.com.cifi.mars.constant.VersionIdentifyEnum;
import cn.com.cifi.mars.constant.VersionStatusEnum;
import cn.com.cifi.mars.constant.VersionTypeEunm;
import cn.com.cifi.mars.entity.MdmProject;
import cn.com.cifi.mars.entity.PriceVersion;
import cn.com.cifi.mars.entity.common.IdmUser;
import cn.com.cifi.mars.entity.common.ProjectByStages;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.service.ProjectConsoleService;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.NumberUtils;
import cn.com.cifi.mars.util.StrUtils;

/**
 * 工作台
 * 
 * @author Administrator
 *
 */
@RestController
public class ProjectConsoleController extends BaseAction implements IProjectConsoleController {
	
	@Autowired
	private IdmUserService idmUserService;
	
	@Autowired
	private ProjectConsoleService projectConsoleService;
	
	@Value("${underway_price_base_url}")
	private  String priceBaseUrl;
	
	@Value("${underway_sign_base_url}")
	private  String signBaseUrl;

	@Value("${underway_return_base_url}")
	private  String returnBaseUrl;

	/**
	 * 工作台-项目指标（全部项目）
	 */
	@Override
	public R<AllProjectIndexVO> getAllProjectIndex(String apiVersion) {
		String userName = getOperator().getUsername();
		String date = LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyy-MM");
		AllProjectIndexVO vo = new AllProjectIndexVO();
		//获取用户权限的所有项目（项目总数）
		List<String> projectIds = prepareUserDataPermission(userName);
		if(CollectionUtils.isEmpty(projectIds)) {
			return ok(vo);
		}
		//存在货值的项目数
		List<ProjectCountDto> countList = projectConsoleService.selectProjectCountList(projectIds,date);
		List<ProjectCountDto> firstCount = countList.stream().filter(projectCountDto -> projectCountDto.getIsFirstOpen().intValue()==1).collect(Collectors.toList());
		List<ProjectCountDto> continueCount = countList.stream().filter(projectCountDto -> projectCountDto.getIsContinueOpen().intValue()==1).collect(Collectors.toList());
		
		AllProjectIndexDto dto = projectConsoleService.selectAllProjectIndex(projectIds,date);
		
		vo.setProjectTotalCount(countList.size());
		vo.setFirstProjectCount(firstCount.size());
		vo.setRenewalSaleProjectCount(continueCount.size());
		if(dto != null) {
			vo.setTotalValue(dto.getTotalPrice());
			vo.setEquityTotalValue(dto.getEquityPrice());
			vo.setSelfSupportValue(dto.getStagePrice());
			
			vo.setSoldValue(dto.getSoldPrice());
			vo.setEquitySoldValue(dto.getSoldEquityPrice());
			vo.setSoldEquityRate(NumberUtils.divide(dto.getSoldEquityPrice(), dto.getSoldPrice(), 4));
			
			vo.setStockValue(dto.getUnSalePrice());
			vo.setEquityStockValue(dto.getUnSaleEquityPrice());
			vo.setStockEquityRate(NumberUtils.divide(dto.getUnSaleEquityPrice(), dto.getUnSalePrice(), 4));
			
			vo.setPlanValue(dto.getPlanPrice());
			vo.setEquityOnTheWayValue(dto.getPlanEquityPrice());
			vo.setPlanEquityRate(NumberUtils.divide(dto.getPlanEquityPrice(), dto.getPlanPrice(), 4));
			
			vo.setSoilStorageValue(dto.getLandHkPrice());
			vo.setEquitySoilStorageValue(dto.getLandHkEquityPrice());
			vo.setSoilStorageEquityRate(NumberUtils.divide(dto.getLandHkEquityPrice(), dto.getLandHkPrice(), 4));
		}
		return ok(vo);
	}
	
	/**
	 * 
	 * @Description：获取用户项目数据权限（存在货值版本）
	 * @param userName
	 * @return List<String>
	 * @author：yyd
	 * @date：2020年3月9日 下午6:41:04
	 */
	private List<String> prepareUserDataPermission(String userName) {
        List<String> projects = Collections.synchronizedList(new ArrayList<>());
        List<ProjectByStagesDto> dataPermissionList = idmUserService.queryUserDataPermissions(userName);
        if (CollectionUtils.isNotEmpty(dataPermissionList)) {
        	List<PriceVersion> versionList = projectConsoleService.selectAllProject();
        	 for (ProjectByStagesDto dto : dataPermissionList) {
                 if (dto.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_31.getKey())) {
                	 for(PriceVersion version : versionList) {
                		 if(dto.getOrgdepid().equals(version.getProjectId())) {
                			 projects.add(dto.getOrgdepid());
                		 }
                	 }
                 }
             }
        } 
        return projects;
    }
	
	/**
	 * 工作台-项目概览
	 */
	@Override
	public R<List<ProjectOverviewVO>> getPorjectStagePageList(String apiVersion, String currentPage, String pageSize,String projectName) {
		List<ProjectOverviewVO> list =  Collections.synchronizedList(new ArrayList<>());
		Map<String, Object> resMap = new HashMap<>();
		String date = LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyy-MM");
		String userName = getOperator().getUsername();
		//获取用户权限的所有项目Id
		List<String> projectIds = prepareUserDataPermission(userName);
		if(CollectionUtils.isEmpty(projectIds)) {
			return ok(list);
		}
		int totalCount = projectConsoleService.selectTotalCount(projectIds,projectName);
		//分页获取项目信息
		List<MdmProject> projectList = projectConsoleService.selectProjectByDataPermission(projectIds,currentPage,pageSize,projectName);
		if(CollectionUtils.isNotEmpty(projectList)) {
			//各项目总货值
			List<ProjectValueDto> projectValueList = projectConsoleService.selectProjectValueList(projectList,date);
			
			//项目所有分期
			List<ProjectStagesDto> stageList = projectConsoleService.queryProjectStageList(projectList);
			//项目分期版本数据
			List<ProjectStagesVersionDto> versionDataList = projectConsoleService.selectVersionDataList(projectList); 
			for(MdmProject project : projectList) {
				ProjectOverviewVO vo = new ProjectOverviewVO();
				vo.setProjectId(project.getProjectId());
				vo.setProjectName(project.getProjectName());
				
				if(CollectionUtils.isNotEmpty(projectValueList)) {
					for(ProjectValueDto valueDto : projectValueList) {
						if(valueDto.getProjectId().equals(project.getProjectId())) {
							vo.setProjectTotalValue(valueDto.getTotalPrice());
							vo.setProjectEquityValue(valueDto.getEquityPrice());
							vo.setProjectEquityRate(NumberUtils.divide(valueDto.getEquityPrice(), valueDto.getTotalPrice(), 4));
						}
					}
				}
				
				List<ProjectStageVO> projectStageList = Collections.synchronizedList(new ArrayList<>());
				for(ProjectStagesDto stage : stageList) {
					if(project.getProjectId().equals(stage.getProjectId())) {
						ProjectStageVO stageVo = new ProjectStageVO();
						stageVo.setStageId(stage.getStageId());
						stageVo.setStageCode(stage.getStageCode());
						stageVo.setStageName(stage.getStageName());
						List<ProjectVersionVO> versionList = Collections.synchronizedList(new ArrayList<>());
						stageVo.setVersionList(versionList);
						projectStageList.add(stageVo);
						for(ProjectStagesVersionDto version : versionDataList) {
							if(version.getStageId().equals(stage.getStageId())) {
								ProjectVersionVO versionVo = new ProjectVersionVO();
								versionVo.setBussnessType(version.getType());
								versionVo.setVersionName(prepareVersionName(version));
								versionVo.setVersionType(version.getVersionType());
								versionVo.setVersionStatus(VersionStatusEnum.getValueByKey(version.getVersionState()));
								versionVo.setPrice(version.getPrice());
								if(StrUtils.isEmpty(version.getNotice())) {
									versionVo.setIsTodo(0);
								}else {
									versionVo.setIsTodo(1);
									versionVo.setUrl(prepareToUrl(project.getProjectId(),stage.getStageId(),version.getVersionType(),version.getVersionId(),"货值填报"));
								}
								versionList.add(versionVo);
							}
						}
					}
				}
				
				List<ProjectStageVO> sortStageList = sortStage(projectStageList);
				vo.setProjectStageList(sortStageList);
				list.add(vo);
			}
			
			resMap.put("total", totalCount);
			resMap.put("list", list);
		}
		return ok(resMap);
	}
	/**
	 * 
	 * @Description：分期排序
	 * @author：yyd
	 * @date：2020年3月10日 下午4:59:07
	 */
	private List<ProjectStageVO> sortStage(List<ProjectStageVO> projectStageList) {
		List<ProjectStageVO> list = Collections.synchronizedList(new ArrayList<>());
		if(CollectionUtils.isNotEmpty(projectStageList)){
			projectStageList.sort((a, b) -> {
                 String aCode = a.getStageCode();
                 String bCode = b.getStageCode();

                 if(StrUtils.isNotEmpty(aCode)) {
                	if(aCode.indexOf('.') >=0) {
                		aCode = aCode.substring(aCode.indexOf('.')+1, aCode.length());
                	}else {
                		aCode = "0";
                	}
                 }
                 
                 if(StrUtils.isNotEmpty(bCode)) {
                 	if(bCode.indexOf('.') >=0) {
                 		bCode = bCode.substring(bCode.indexOf('.')+1, bCode.length());
                 	}else {
                 		aCode = "0";
                 	}
                  }
                 if(StrUtils.isEmpty(aCode)) {
  		        	return 1; 
  		         }else if(StrUtils.isEmpty(bCode)) {
  		        	 return -1;
  		         }else if(StrUtils.isNotEmpty(aCode) && StrUtils.isNotEmpty(bCode)) {
  		        	 return Integer.valueOf(aCode) - Integer.valueOf(bCode);
  		         }
 	     		 return 0;
             });
			list.addAll(projectStageList);
         }
		return list;
	}

	/**
	 * 工作台-项目概览-分期版本列表
	 */
	@Override
	public R<List<ProjectVersionVO>> getStageList(String apiVersion, String stageId) {
		List<ProjectVersionVO> list =  Collections.synchronizedList(new ArrayList<>());
		List<ProjectStagesVersionDto> versionDataList = projectConsoleService.selectVersionDataListByStageId(stageId);
		if(CollectionUtils.isNotEmpty(versionDataList)) {
			for(ProjectStagesVersionDto dto : versionDataList) {
				ProjectVersionVO versionVo = new ProjectVersionVO();
				versionVo.setBussnessType(dto.getType());
				versionVo.setVersionName(prepareVersionName(dto));
				versionVo.setVersionType(dto.getVersionType());
				versionVo.setVersionStatus(VersionStatusEnum.getValueByKey(dto.getVersionState()));
				versionVo.setPrice(dto.getPrice());
				//TODO:待办消息
				versionVo.setIsTodo(1);
				list.add(versionVo);
			}
		}
		return ok(list);
	}
	
	/**
	 * 项目工作台-指定项目指标数据
	 */
	@Override
	public R<ProjectIndexVO> getProjectIndex(String apiVersion, String projectId) {
		String date = LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyy-MM");
		ProjectIndexVO data = projectConsoleService.selectProjectIndex(projectId,date);
		if(data == null) {
			data = new  ProjectIndexVO();
		}
		return ok(data);
	}
	
	/**
	 * 项目工作台-正在进行列表
	 */
	@Override
	public R<List<ProjectUnderwayVO>> getProjectUnderwayList(String apiVersion, String projectId) {
		List<ProjectUnderwayVO> resList =  Collections.synchronizedList(new ArrayList<>());
		List<ProjectUnderwayDto> list = projectConsoleService.selectUnderwayList(projectId);
		if(CollectionUtils.isNotEmpty(list)) {
			for(ProjectUnderwayDto dto : list) {
				ProjectUnderwayVO vo = new ProjectUnderwayVO();
				vo.setStageName(dto.getStageName());
				vo.setBusinessType(dto.getBusinessType());
				vo.setVersion(prepareVersionName(dto));
				vo.setVersionStatus(VersionStatusEnum.getValueByKey(dto.getVersionStage()));
				vo.setUpdateTime(dto.getUpdateTime());

				if(dto.getCreateBy().equals(Constants.SYS)){
					vo.setCreateBy("系统");
				}else {
					IdmUser user = idmUserService.getByAlias(dto.getCreateBy());
					if(user != null) {
						vo.setCreateBy(user.getUsercn());
					}
				}
				vo.setToDoDetail(prepareToDoDetail(dto.getBusinessType(),dto.getVersionStage()));
				vo.setUrl(prepareToUrl(projectId,dto.getStageId(),dto.getVersionType(),dto.getVersionId(),dto.getBusinessType()));
				
				resList.add(vo);
			}
		}
		return ok(resList);
	}

	private String prepareToDoDetail(String type,String status) {
		String toDoDetail = "";
		if(type.equals("货值填报")) {
			if(status.equals(VersionStatusEnum.NOTPREPARED.getKey())) {
				toDoDetail = "请填报货值";
			}else if(status.equals(VersionStatusEnum.ORGANIZATION.getKey())){
				toDoDetail = "请填报货值并发起审批";
			}else if(status.equals(VersionStatusEnum.EXAMINEDAPPROVED.getKey())){
				toDoDetail = "请发起审批并提交到OA审批";
			}else if(status.equals(VersionStatusEnum.APPROVED.getKey())){
				toDoDetail = "请跟进审批结果";
			}else if(status.equals(VersionStatusEnum.FAILUREAPPROVED.getKey())){
				toDoDetail = "请重新填报货值并发起审批";
			}
		}else if (type.equals("签约计划")){
			if(status.equals(VersionStatusEnum.NOTPREPARED.getKey())) {
				toDoDetail = "请编排签约计划";
			}else if(status.equals(VersionStatusEnum.ORGANIZATION.getKey())){
				toDoDetail = "请编排签约计划并发起审批";
			}else if(status.equals(VersionStatusEnum.EXAMINEDAPPROVED.getKey())){
				toDoDetail = "请发起审批并提交到OA审批";
			}else if(status.equals(VersionStatusEnum.APPROVED.getKey())){
				toDoDetail = "请跟进审批结果";
			}else if(status.equals(VersionStatusEnum.FAILUREAPPROVED.getKey())){
				toDoDetail = "请重新编排签约计划并发起审批";
			}
		}else if (type.equals("回款计划")){
			if(status.equals(VersionStatusEnum.NOTPREPARED.getKey())) {
				toDoDetail = "请编排回款计划";
			}else if(status.equals(VersionStatusEnum.ORGANIZATION.getKey())){
				toDoDetail = "请编排回款计划并发起审批";
			}else if(status.equals(VersionStatusEnum.EXAMINEDAPPROVED.getKey())){
				toDoDetail = "请发起审批并提交到OA审批";
			}else if(status.equals(VersionStatusEnum.APPROVED.getKey())){
				toDoDetail = "请跟进审批结果";
			}else if(status.equals(VersionStatusEnum.FAILUREAPPROVED.getKey())){
				toDoDetail = "请重新编排回款计划并发起审批";
			}
		}
		return toDoDetail;
	}
	
	/**
	 * 
	 * @Description：拼接跳转链接
	 * @author：yyd
	 * @date：2020年3月9日 下午9:54:10
	 */
	private String prepareToUrl(String projectId,String stageId,String versionType,String versionId,String bussnessType) {
		List<ProjectByStages> parentList = projectConsoleService.selectParentData(projectId);
		String baseUrl = "";
		String businessId="";
		String cityId="";
		if(CollectionUtils.isNotEmpty(parentList)) {
			for(ProjectByStages obj : parentList) {
				String typeId = obj.getHrOrgTypeId();
				if(typeId.equals(HrOrgTypeEunm.ORG_21.getKey())) {
					cityId = obj.getOrgdepid();
				}else if(typeId.equals(HrOrgTypeEunm.ORG_20.getKey())) {
					businessId = obj.getOrgdepid();
				}
			}
		}
		if(bussnessType.equals("货值填报")) {
			baseUrl = priceBaseUrl;
		}else if (bussnessType.equals("签约计划")){
			baseUrl =signBaseUrl;
		}else {
			baseUrl =returnBaseUrl;
		}
		return baseUrl+businessId+"/"+cityId+"/"+projectId+"/"+stageId+"/"+versionType+"/"+versionId;
	}
	
	private String prepareVersionName(ProjectStagesVersionDto version) {
		String versionName="";
		if(version != null) {
			String versionTypeName = VersionTypeEunm.getValueByKey(version.getVersionType());
			String versionNum = version.getVersionNum();
			String lastDate = "";
			String affiliationMonth = "";
			if(version.getUpdateTime() != null) { 
				lastDate = LocalDateTimeUtils.formatTime(version.getUpdateTime(), "yyyyMMdd");
			}else {
				lastDate = LocalDateTimeUtils.formatTime(version.getCreateTime(), "yyyyMMdd");
			}
			if(version.getVersionType().equals(VersionTypeEunm.INVESTMENT.getKey()) || version.getVersionType().equals(VersionTypeEunm.WARPLAN.getKey())) {
				String assessmentTag="";
				if(version.getIsAssessmentVersion() != null && version.getIsAssessmentVersion().intValue() == 1) {
					assessmentTag = "(考核版)";
				}
				versionName = versionTypeName + version.getVersionNum() + "-" + lastDate+assessmentTag;
			}else if(version.getVersionType().equals(VersionTypeEunm.BUDGET.getKey())) {
				if(StrUtils.isEmpty(version.getVersionIdentify())) {
					versionName = version.getBudgetYear()+"预算版"+versionNum+"-"+lastDate;
				}else {
					if(version.getVersionIdentify().equals(VersionIdentifyEnum.ALL_YEAR.getKey()) ||
							version.getVersionIdentify().equals(VersionIdentifyEnum.MID_YEAR.getKey())	) {
						versionName = version.getBudgetYear()+VersionIdentifyEnum.getValueByKey(version.getVersionIdentify())+"预算版"+versionNum+"-"+lastDate;
					}else {
						versionName = version.getVersionIdentify()+versionNum+"-"+lastDate;
					}
				}
			}else {
				if(StrUtils.isNotEmpty(version.getVersionDate())) {
					affiliationMonth = version.getVersionDate().replace("-","");
				}
				versionName = affiliationMonth+"月动态版"+version.getVersionNum()+"-"+lastDate;
			}
		}
		return versionName;
	}
	
	private String prepareVersionName(ProjectUnderwayDto version) {
		String versionName="";
		if(version != null) {
			String versionTypeName = VersionTypeEunm.getValueByKey(version.getVersionType());
			String affiliationMonth = "";
			if(version.getVersionType().equals(VersionTypeEunm.INVESTMENT.getKey())) {
				String assessmentTag="";
				if(version.getIsAssessmentVersion() != null && version.getIsAssessmentVersion().intValue() == 1) {
					assessmentTag = "(考核版)";
					versionName = versionTypeName + version.getVersionNum() + "-"+assessmentTag;
				}else {
					versionName = versionTypeName + version.getVersionNum();
				}
			}else if(version.getVersionType().equals(VersionTypeEunm.WARPLAN.getKey())) {
				versionName = versionTypeName + version.getVersionNum();
			} else if(version.getVersionType().equals(VersionTypeEunm.BUDGET.getKey())) {
				versionName = version.getVersionIdentify()+version.getVersionNum();
			}else {
				if(StrUtils.isNotEmpty(version.getVersionDate())) {
					affiliationMonth = version.getVersionDate().replace("-","");
				}
				versionName = affiliationMonth+"月动态版"+version.getVersionNum();
			}
		}
		return versionName;
	}
	

}
